//webSocket封装构造函数
function NewWebSocket() {
    this.websocket = null
    this.heartbeat_timer = null
    this.active_close = null
    this.init = (params) => {
        this.websocket = new WebSocket(params.url)
        this.websocket.onopen = (data) => {
            this.heartbeat()
            if (params.onopen) {
                params.onopen('webSocket已连接', data)
            }
        }
        this.websocket.onmessage = (data) => {
            if (params.onmessage) {
                params.onmessage(data.data)
            }
        }
        this.websocket.onclose = () => {
            clearInterval(this.heartbeat_timer)
            if (this.active_close) {
                if (params.onclose) {
                    params.onclose('连接已手动关闭')
                }
            }
        }
        this.websocket.onerror = () => {
            clearInterval(this.heartbeat_timer)
            console.log('连接发生错误！等待五秒后重连');
            setTimeout(() => {
                this.reconnect(params)
            }, 5000)
        }
    }
    this.heartbeat = () => {
        console.log('执行心跳')
        if (this.heartbeat_timer) {
            clearInterval(this.heartbeat_timer)
        }
        this.heartbeat_timer = setInterval(() => {
            this.websocket.send('heartbeat')
        }, 10000)
    }
    this.reconnect = (params) => {
        console.log('执行重连')
        this.active_close = false
        if (this.websocket) {
            this.websocket.close()
        }
        this.init(params)
    }
    this.send = (params) => {
        if (params) {
            this.websocket.send(params)
        }
    }
    this.close = () => {
        console.log('手动关闭，无需重连')
        clearInterval(this.heartbeat_timer)
        this.active_close = true
        this.websocket.close()
    }
}